<?php
/**
 * 生成省市区三级联动JSON文件 - Web版本
 */

// 引入数据库配置
require_once __DIR__ . '/../config/database.php';

// 获取数据库配置
$dbConfig = include __DIR__ . '/../config/database.php';
$config = $dbConfig['connections']['mysql'];

header('Content-Type: text/plain; charset=utf-8');

try {
    // 连接数据库
    $dsn = "mysql:host={$config['hostname']};dbname={$config['database']};port={$config['hostport']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['username'], $config['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "数据库连接成功\n";
    
    // 查询所有省份(level=1)
    $stmt = $pdo->query("SELECT id, name FROM oa_region WHERE level = 1");
    $provinces = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "查询到省份数量: " . count($provinces) . "\n";
    
    $regionData = [];
    
    // 遍历省份 (限制前10个以避免超时)
    $count = 0;
    foreach ($provinces as $province) {
        if ($count >= 10) break; // 限制数量以避免超时
        
        $provinceItem = [
            'id' => $province['id'],
            'name' => $province['name'],
            'children' => []
        ];
        
        // 查询该省份下的所有城市(level=2)
        $cities = $pdo->prepare("SELECT id, name FROM oa_region WHERE parent_id = ? AND level = 2");
        $cities->execute([$province['id']]);
        $cities = $cities->fetchAll(PDO::FETCH_ASSOC);
        
        // 遍历城市
        foreach ($cities as $city) {
            $cityItem = [
                'id' => $city['id'],
                'name' => $city['name'],
                'children' => []
            ];
            
            // 查询该城市下的所有区县(level=3)
            $districts = $pdo->prepare("SELECT id, name FROM oa_region WHERE parent_id = ? AND level = 3");
            $districts->execute([$city['id']]);
            $districts = $districts->fetchAll(PDO::FETCH_ASSOC);
            
            // 添加区县到城市
            foreach ($districts as $district) {
                $cityItem['children'][] = [
                    'id' => $district['id'],
                    'name' => $district['name']
                ];
            }
            
            // 添加城市到省份
            $provinceItem['children'][] = $cityItem;
        }
        
        // 添加省份到数据
        $regionData[] = $provinceItem;
        $count++;
    }
    
    // 生成JSON文件
    $jsonData = json_encode($regionData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    $filePath = __DIR__ . '/static/region.json';
    
    // 确保目录存在
    $dir = dirname($filePath);
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    
    // 写入文件
    if (file_put_contents($filePath, $jsonData)) {
        echo "省市区三级联动JSON文件生成成功！文件路径：{$filePath}\n";
        echo "处理的省份数量: " . count($regionData) . " 个\n";
        echo "JSON文件大小: " . round(strlen($jsonData) / 1024, 2) . " KB\n";
        echo "JSON文件内容预览：\n";
        echo substr($jsonData, 0, 1000) . "...\n";
    } else {
        echo "文件写入失败！\n";
    }
    
} catch (Exception $e) {
    echo "错误：" . $e->getMessage() . "\n";
}